<template>
<div>
  <!-- 面包屑导航区域 -->
<el-breadcrumb separator-class="el-icon-arrow-right">
  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
  <el-breadcrumb-item>用户管理</el-breadcrumb-item>
  <el-breadcrumb-item>用户列表</el-breadcrumb-item>
</el-breadcrumb>
<el-card>
  <el-row :gutter="20">
    <el-col :span = "7">
      <el-input placeholder="请输入用户姓名" v-model="queryInfo.query">
        <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
      </el-input>

      </el-col>
    <el-col :span = "4">
      <!-- 添加用户的对话框 -->
      <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" :before-close="handleClose">
        <!-- 表单主题区域 -->
        <el-form :model="addForm" :rules="addruleForm" ref="addFormRef" label-width="100px" @close="resetForm()">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addUser()">确 定</el-button>
        </span>
      </el-dialog>
    </el-col>
  </el-row>
  <el-table
    :data="UserList" stripe border style="width: 100%">
    <el-table-column type="index"></el-table-column>
    <el-table-column prop="username" label="姓名"> </el-table-column>
    <el-table-column prop="role_name" label="角色"></el-table-column>
    <el-table-column prop="email" label="地址"> </el-table-column>
    <el-table-column prop="mobile" label="手机号"> </el-table-column>
    <el-table-column prop="mg_state" label="状态">
      <template slot-scope="scope">
        <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)">
        </el-switch>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="180px">
     <template slot-scope="scope">
       <!-- 修改按钮 -->
       <el-tooltip class="item" effect="dark" content="修改用户" placement="top" :enterable="false">
         <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUser(scope.row)"></el-button>
      </el-tooltip>
      <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%" :before-close="handleClose">
        <!-- 表单主题区域 -->
        <el-form :model="editUserInfo" :rules="addruleForm" ref="editFormRef" label-width="100px" @close="resetForm()">
          <el-form-item label="用户id" prop="id">
            <el-input v-model="editUserInfo.id" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editUserInfo.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editUserInfo.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editUserSubmit ()">确 定</el-button>
        </span>
      </el-dialog>
        <!-- 删除按钮 -->
        <el-tooltip class="item" effect="dark" content="删除用户" placement="top" :enterable="false">
         <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUser(scope.row.id)"></el-button>
        </el-tooltip>
        <!-- 设置用户权限 -->
        <el-tooltip class="item" effect="dark" content="设置用户权限" placement="top" :enterable="false">
          <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
        </el-tooltip>
     </template>
    </el-table-column>
  </el-table>

   <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[1, 2, 5, 10]"
      :current-page="queryInfo.pagenum"
      :page-size="queryInfo.pagesize"
      :total = total
      layout="total, sizes, prev, pager, next, jumper"
      >
    </el-pagination>
</el-card>

<!-- 卡片区域 -->
</div>

</template>
<script>
export default {
  data () {
    // 验证邮箱的规则
    var checkEmail = (rule, value, callback) => {
      const regMobile = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的电子邮箱'))
    }
    // 验证手机号的规则
    var checkMoblie = (rule, value, callback) => {
      const regMobile = /^1\d{10}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的电话号码'))
    }
    return {

      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''

      },
      // 添加用户的表单规则对象
      addruleForm: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮件', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMoblie, trigger: 'blur' }
        ]
      },
      UserList: [],
      total: '',
      addDialogVisible: false,
      editDialogVisible: false,
      // 获取用户列表的参数
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 编辑用户信息的参数
      editUserInfo: {
        id: '',
        email: '',
        mobile: ''
      }
    }
  },
  created () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.UserList = res.data.users
      this.total = res.data.total
    },
    handleSizeChange (val) {
      this.queryInfo.pagesize = val
      this.getUserList()
    },
    handleCurrentChange (val) {
      this.queryInfo.pagenum = val
      this.getUserList()
    },
    // 监听swich开关的改变
    async userStateChange (state) {
      const { data: res } = await this.$http.put(`users/${state.id}/state/${state.mg_state}`)
      if (res.meta.status !== 200) {
        state.mg_state = !state.mg_state
        return this.$message.error('用户状态修改失败')
      }
    },
    resetForm (formName) {
      // 重置表单
      // console.log(this.$refs.addFormRef)
      this.$refs.addFormRef.resetFields()
    },
    addUser () {
      // 表单预验证
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)

        this.$message.success('用户添加成功')
        this.addDialogVisible = false
      })
    },
    editUser (user) {
      this.editDialogVisible = true
      this.editUserInfo = user
    },
    editUserSubmit () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put('users/' + this.editUserInfo.id, {
          mobile: this.editUserInfo.mobile, email: this.editUserInfo.email
        })
        if (res.meta.status !== 200) {
          return this.$message.error('数据更新失败')
        }
        this.editDialogVisible = false
      })
    },
    async removeUser (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('删除成功')
      this.getUserList()
    }
  }
}
</script>
<style scoped>
.el-breadcrumb{
  margin-bottom:15px;
  font-size: 12px;
}
.el-card{
  box-shadow: 0 1px 1px rgba(0,0,0,0.25)!important;
}
</style>>
